package main;

import java.io.IOException;
import java.io.PrintStream;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import translationModels.TParam;

public class OutputData
{
	private TrainingData trainingData;
	private HashMap<TParam, Double> tParams;
	private ArrayList<HashMap<Integer, Integer>> alignments;
	
	public OutputData(TrainingData trainingData, HashMap<TParam, Double> tParams, ArrayList<HashMap<Integer, Integer>> alignments)
	{
		this.trainingData = trainingData;
		this.tParams = tParams;
		this.alignments = alignments;
	}
	
	public void writeOutput(String outputFile) throws IOException
	{
		PrintStream writer = new PrintStream(outputFile);
		
		for (int i = 0; i < alignments.size(); i++)
		{
			for (int j = 0; j < trainingData.getSentences().get(i).getKey().length(); j++)
			{
				Integer eIndex = alignments.get(i).get(j);
				if ((eIndex != null) && (eIndex != -1))
					writer.print(j + "-" + eIndex + " ");
			}
			writer.println();
		}
		
		writer.close();
	}
	
	public void writeTParams(String outputFile) throws IOException
	{
		HashMap<String, ArrayList<SimpleEntry<String, Double>>> outputParams = new HashMap<String, ArrayList<SimpleEntry<String,Double>>>();
		
		// Sort the t params
		for (TParam tParam : tParams.keySet())
		{
			if (!outputParams.containsKey(tParam.f))
				outputParams.put(tParam.f, new ArrayList<SimpleEntry<String,Double>>());
			outputParams.get(tParam.f).add(new SimpleEntry<String, Double>(tParam.e, tParams.get(tParam)));
		}
		
		// Output the t params
		PrintStream writer = new PrintStream(outputFile);
		for (String f : outputParams.keySet())
		{
			// Sort by best translation
			Collections.sort(outputParams.get(f), new Comparator<SimpleEntry<String, Double>>()
			{
				@Override
				public int compare(SimpleEntry<String, Double> arg0, SimpleEntry<String, Double> arg1)
				{
					double diff = arg1.getValue() - arg0.getValue();
					if (diff < 0)
						return -1;
					if (diff == 0)
						return 0;
					return 1;
				}
			});
			
			for (SimpleEntry<String, Double> entry : outputParams.get(f))
				writer.println("t(" + f + "|" + entry.getKey() + ")=" + entry.getValue());
		}
		writer.close();
	}
}
